import socket as soc
import sys
import time

class Socket_Client:
    def __init__(self,host='127.0.0.1',port=51423):

        self.host=host
        self.port=port
        self.s=soc.socket(soc.AF_INET,soc.SOCK_STREAM)

    def Connect(self):
        try:
            self.s.connect((self.host,self.port))
        except soc.gaierror as e:
            print('地址错误:'+str(e))
            sys.exit(1)
        except soc.error as e:
            print('连接错误:'+str(e))
            sys.exit(1)
        self.s.send('算法已上线'.encode())
        receive=self.s.recv(1024).decode()
        return receive

    def Send_Receive(self,message):
        self.s.send(message.to_string().encode())
        message=self.s.recv(1024)
        while message is None:
            message=self.s.recv(1024)
        return self.Unpack(message)

    def Send(self,message):
        self.s.send(message.to_string().encode())

    def Receive(self):
        rece=self.s.recv(1024)
        while rece is None:
            rece=self.s.recv(1024)
        return self.Unpack(rece)


    def Unpack(self,byte):
        return byte.decode()

    # def ping(self):
